package com.mediacloud.app.newsmodule.activity;

import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.chinamcloud.collect.AcquisitionManager;
import com.chinamcloud.report.ReportKit;
import com.eventTrack.CDPTrackReportManager;
import com.mediacloud.app.appfactory.cache.UserRecommend;
import com.mediacloud.app.assembly.util.DateParse;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.cloud.ijkplayersdk.auth.AuthMode;
import com.mediacloud.app.cloud.ijkplayersdk.auth.URLAuth;
import com.mediacloud.app.cloud.ijkplayersdk.video.VideoPlayer;
import com.mediacloud.app.controller.ControllerWarp;
import com.mediacloud.app.controller.live.IProgram;
import com.mediacloud.app.controller.live.OnLookBackTimeStampChangedListener;
import com.mediacloud.app.controller.live.ProgramMod;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.ProgramListItem;
import com.mediacloud.app.model.news.ProgramListItem.GuideItemState;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.model.news.ShowSwitch;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.comment.x.XCommentActivity;
import com.mediacloud.app.newsmodule.broadcast.LiveReplayBroadcast;
import com.mediacloud.app.newsmodule.broadcast.LiveReplayBroadcast.LiveReplayHandle;
import com.mediacloud.app.newsmodule.broadcast.PowerStateReciver;
import com.mediacloud.app.newsmodule.fragment.NotifyMicroEvent;
import com.mediacloud.app.newsmodule.fragment.recommend.ComponentLiveListFragment;
import com.mediacloud.app.newsmodule.fragment.recommend.ComponentLiveListFragment.GetProgramData;
import com.mediacloud.app.newsmodule.model.ProgramListItemX;
import com.mediacloud.app.newsmodule.model.VideoPlayObj;
import com.mediacloud.app.newsmodule.model.VideoPlayObj.VideoLineItem;
import com.mediacloud.app.newsmodule.model.VideoPlayerListenerImpl;
import com.mediacloud.app.newsmodule.newsdetail_component.NewsDetailComponentUtils;
import com.mediacloud.app.newsmodule.pay.PaidContentListener;
import com.mediacloud.app.newsmodule.pay.PaidMetas;
import com.mediacloud.app.newsmodule.pay.VideoPayUtil;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.DisplayCutoutManager;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.GetUrlToolKt;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.LiveMediaPlayBackInvoker;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.ListStyle;
import com.mediacloud.app.reslib.enums.TitileType;
import com.mediacloud.app.reslib.enums.XKey;
import com.mediacloud.app.user.model.UserInfo;
import com.tencent.mmkv.MMKV;
import com.utils.UriTool;
import com.yoake.media.player.utils.OnPlayerActionListener;
import com.yoake.media.player.utils.XVideoBitRate;
import com.yoake.media.player.utils.XVideoSpeed;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import kotlin.Unit;
import kotlin.jvm.functions.Function4;
import xyz.doikki.videoplayer.player.VideoView;


/**
 * 视频直播
 */
public class VideoLiveDetailActivity extends StyleSetActivity implements LiveReplayHandle, DataInvokeCallBack<ArticleItemReciver>, GetProgramData, OnLookBackTimeStampChangedListener {
    protected boolean isAutoPlay;
    protected VideoPlayer mBaiduPlayer;
    protected TextView liveChannelName, channelDes, showMoreDes;
    protected ImageView arrowIco;
    NewsDetailInvoker newsDetailInvoker;
    protected LiveReplayBroadcast liveReplayBroadcast;
    Map<String, String> lineMap = new LinkedHashMap<String, String>();

    VideoPlayObj videoPlayObj = new VideoPlayObj();

    LiveMediaPlayBackInvoker liveMediaPlayBackInvoker;
    LivePlayBackUrlReciver livePlayBackUrlReciver;
    // LiveProgramTableFragment fragment;
    /*    *//**
     * 链接弹幕服务器用的 融云
     *//*
    DanMu4RongYun danmu4RongYun;*/
    /**
     * 聊天室id
     */
    String chatroomId = "";
    String cdnEncypt;

    //BadgeView badgeView;
    PowerStateReciver powerStateReciver;
    LinearLayout mRelateRootView;
    ComponentLiveListFragment fragment;
    ShowSwitch mShowSwitch;
    //支付相关
    VideoPayUtil videoPayUtil;
    LinearLayout broccoliLayout;
    private View mErrorView;
    private TextView emptyTipsText;
    private ComponentLiveListFragment programsFragment;
    long  mTyReportStartTime=0;
    long  mTyReportEndTime=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isCommentDialog=true;
        super.onCreate(savedInstanceState);
        Uri uriData = getIntent().getData();
        if (uriData != null) {
            isFromH5OpenToReStart =UriTool.INSTANCE.isFromH5OpenToReStart(this,uriData) ;
            String articleid = uriData.getQueryParameter("articleid");
            String title = uriData.getQueryParameter("title");
            String cname = uriData.getQueryParameter("cname");
            String tag = uriData.getQueryParameter("tag");
            catalogItem = new CatalogItem();
            catalogItem.setCatname(cname);
            articleItem = new ArticleItem();
            try {
                articleItem.setTitle(title);
                articleItem.setId(Long.valueOf(articleid));
            } catch (Exception e) {
            }
        } else {
            catalogItem = getIntent().getParcelableExtra("catalog");
            articleItem = getIntent().getParcelableExtra("data");
        }

        try {
            if (catalogItem == null)
                catalogItem = new CatalogItem();
            catalogItem.setCatalog_type(getIntent().getStringExtra("category"));
            catalogItem.setCatid(getIntent().getStringExtra("navigate_id"));
            if (articleItem == null) {
                articleItem = new ArticleItem();
                articleItem.setId(Long.parseLong(getIntent().getStringExtra("article_id")));
                articleItem.setSummary(getIntent().getStringExtra("summary"));
                articleItem.setTitle(getIntent().getStringExtra("title"));
                articleItem.setUrl(getIntent().getStringExtra("url"));
                articleItem.setIsAdvertisement(getIntent().getIntExtra("isAdvertisement", 0));
                articleItem.setIsBarrage(getIntent().getIntExtra("isBarrage", 0));
                articleItem.setReferSourceID(getIntent().getStringExtra("ReferSourceID"));
                articleItem.setIsComment(getIntent().getStringExtra("isComment"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (articleItem != null) {
            readStatus();
            mShowSwitch = articleItem.getmShowSwitch();
        }
        showMoreDes = Utility.findViewById(mRootView, R.id.showMoreDes);
        arrowIco = Utility.findViewById(mRootView, R.id.arrowIco);
        mRelateRootView = Utility.findViewById(mRootView, R.id.relateLayout);
        mBaiduPlayer = Utility.findViewById(mRootView, R.id.mBaiduPlayer);
        mBaiduPlayer.setPlayControllerType(ControllerWarp.TYPE_LIVE);
        mBaiduPlayer.setLiveProgressBarTimeLimit(AppFactoryGlobalConfig.getAppServerConfigInfo(this).getOtherFunction().getLive_progress_bar_time_limit());
        mBaiduPlayer.iPlayerProgramLookBack = this;
        mErrorView = Utility.findViewById(mRootView, R.id.error_view);
        emptyTipsText = Utility.findViewById(mRootView, R.id.emptyTipsText);
        ImageView imagNowork = mErrorView.findViewById(R.id.image_loading);
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.net_not_give_force);
        String network = AppFactoryGlobalConfig.getAppServerConfigInfo(this).getNetwork();
        FunKt.load(imagNowork, network, drawable);
        isAutoPlay = MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false);
        setPlayerView();

        broccoliLayout = Utility.findViewById(mRootView, R.id.broccoliLayout);
        boolean isLeftImgMode = ListStyle.TotoalStyle.LEFT_IMAGE.equals(AppFactoryGlobalConfig.getAppServerConfigInfo(this).getContent_list());
        if (isLeftImgMode) {
            for (int i = 0; i < 3; i++) {
                broccoliLayout.addView(LayoutInflater.from(this).inflate(R.layout.layout_broccoli21, null));
            }
        } else {
            for (int i = 0; i < 3; i++) {
                broccoliLayout.addView(LayoutInflater.from(this).inflate(R.layout.layout_broccoli22, null));
            }
        }
        liveChannelName = Utility.findViewById(mRootView, R.id.liveChannelName);
        channelDes = Utility.findViewById(mRootView, R.id.channelDes);
        //		mBaiduPlayer.canSeek=false;
        newsDetailInvoker = new NewsDetailInvoker(this);
        liveChannelName.setText(articleItem.getTitle());
        liveChannelName.getPaint().setFakeBoldText(true);
        channelDes.setText(articleItem.getSummary());
        if (isAutoPlay)
            KillMusicUtils.stopAPS(this);

        showMoreDes.setOnClickListener(v -> {
            switchSummary();

        });
        arrowIco.setOnClickListener(v -> {
            switchSummary();

        });
        getVideoDetail();
        initBroad();

        livePlayBackUrlReciver = new LivePlayBackUrlReciver();
        liveMediaPlayBackInvoker = new LiveMediaPlayBackInvoker(livePlayBackUrlReciver);


        setNewsTitle();
        videoPayUtil = new VideoPayUtil(this, catalogItem, mBaiduPlayer, new PaidContentListener() {
            @Override
            public void onPaidContent(@NotNull PaidMetas meta) {
                setVideoContent(meta.getVideo());
            }
        });
        onPageStart();
        showPageTransition();
        //设置使用刘海屏幕区域
        new DisplayCutoutManager(this).set(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES);
    }

    private void switchSummary() {
        if (showMoreDes.isSelected()) {
            channelDes.setVisibility(View.GONE);
            arrowIco.animate().rotationBy(-180).start();
        } else {
            channelDes.setVisibility(View.VISIBLE);
            arrowIco.animate().rotationBy(180).start();
        }
        showMoreDes.setSelected(!showMoreDes.isSelected());
    }

    /**
     * 设置视频view
     */
    private void setPlayerView() {
        mBaiduPlayer.hideButtonBack();
        mBaiduPlayer.setAutoPlay(isAutoPlay);
        //		mBaiduPlayer.setDamuEnable(false);
        ViewGroup.LayoutParams layoutParams = mBaiduPlayer.getLayoutParams();
        float num = (float) (16.0 / 9.0);
        layoutParams.height = (int) (getResources().getDisplayMetrics().widthPixels / num);
        mBaiduPlayer.setLayoutParams(layoutParams);
        if (isAutoPlay)
            mBaiduPlayer.showLoadingView();
        mBaiduPlayer.toggleFullScreenEnable(false);
        //mBaiduPlayer.showTogglePlayBtn(View.GONE);
        //mBaiduPlayer.setvideoQualityTitleViseble(View.GONE);
        // mBaiduPlayer.showButtonBack();
        // mBaiduPlayer.showSmallTitle(View.VISIBLE);
        mBaiduPlayer.setSmallView(View.VISIBLE);
        mBaiduPlayer.setSmallBacBtnActivity(this);
        mBaiduPlayer.controlBarViewControl.shareIco.setVisibility(View.GONE);
        mBaiduPlayer.setOnShareClickListener((it) -> shareWrap.show(mRootView));

    }

    protected void setNewsTitle() {
        int base = AppFactoryGlobalConfig.getAppServerConfigInfo(this).getBase();
        if (base == TitileType.FRAME) {
            setFrameTypeTitle();
        } else if (base == TitileType.NAVIGATE) {
            setTitle(catalogItem != null ? catalogItem.getCatname() : "");
        } else if (base == TitileType.NEWS_TITLE) {
            setTitle(articleItem != null ? articleItem.getTitle() : "");
        } else if (base == TitileType.NOTITLE) {
            setTitle("");
        }

    }


    protected void initBroad() {
        liveReplayBroadcast = new LiveReplayBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LiveReplayBroadcast.PlayAction);
        LocalBroadcastManager.getInstance(this).registerReceiver(liveReplayBroadcast, intentFilter);
        liveReplayBroadcast.liveReplayHandle = this;


        powerStateReciver = new PowerStateReciver();
        IntentFilter powerFilter = new IntentFilter();
        powerFilter.addAction(Intent.ACTION_POWER_CONNECTED);
        powerFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        registerReceiver(powerStateReciver, powerFilter);
    }


    @Override
    public void onBackPressed() {
        if (mBaiduPlayer != null && mBaiduPlayer.isFullScreen()) {
            mBaiduPlayer.toggleFullScreen();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mBaiduPlayer != null) {
            if (Intent.ACTION_POWER_CONNECTED.equals(powerStateReciver.getState())) {
                mBaiduPlayer.isHandModePause = true;
            } else {
                mBaiduPlayer.isHandModePause = false;
                mBaiduPlayer.pagePause = true;
                if (!commentIsOpen)
                mBaiduPlayer.pause();
            }
            powerStateReciver.setState(null);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mBaiduPlayer != null && !mBaiduPlayer.isHandModePause) {
            mBaiduPlayer.resume();
        }
        connectRongYun();
    }


    @Override
    public int getStatusBarColor() {
        if (mBaiduPlayer != null && mBaiduPlayer.isFullScreen())
            return Color.TRANSPARENT;
        return Color.BLACK;

    }

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_activity_videolive_detail;
    }

    protected void getVideoDetail() {
        String navigate_id = catalogItem != null ? catalogItem.getCatid() : "";
        newsDetailInvoker.getArticleById("" + articleItem.getId(),  navigate_id);
    }

    @Override
    public boolean showTitleBar() {
        return false;
    }

    boolean isStop = false;
    long startPosition = 0L;
    protected void setVideoPlayerData() {

        mBaiduPlayer.setOnPlayerListener(new VideoPlayerListenerImpl() {
            @Override
            public void onPrepared(int currentMediaIndex) {
                super.onPrepared(currentMediaIndex);
                startPosition = mBaiduPlayer.getcurrentPlayPosition();
                if (programsFragment != null) {
                    programsFragment.setPlay();
                }
                try {
                    KillMusicUtils.stopAPS(VideoLiveDetailActivity.this);
                }catch (Exception e){}
                mBaiduPlayer.toggleFullScreenEnable(true);
            }

            @Override
            public void onError(int currentMediaIndex, int arg1, int arg2) {
                super.onError(currentMediaIndex, arg1, arg2);
            }

            @Override
            public void onpause(int currentMediaIndex) {
                super.onpause(currentMediaIndex);
                if (!isStop){
                    CDPTrackReportManager.getInstance().LiveChannelStopPlay(articleItem,mBaiduPlayer.getcurrentPlayPosition()-startPosition);
                    isStop = true;
                }
            }

            @Override
            public void onResume(int currentMediaIndex) {
                super.onResume(currentMediaIndex);
                startPosition = mBaiduPlayer.getcurrentPlayPosition();
                isStop = false;
                CDPTrackReportManager.getInstance().LiveChannelStartPlay(articleItem);

            }

            @Override
            public void ontoggleFullScreen(int currentMediaIndex, boolean isFullScreen) {
                super.ontoggleFullScreen(currentMediaIndex, isFullScreen);
                //  VideoPlayerCollectionState.setCollectionState(VideoLiveDetailActivity.this, articleItem, mBaiduPlayer);
                DisplayCutoutManager dcm = new DisplayCutoutManager(VideoLiveDetailActivity.this);
                if (!isFullScreen) {
                    mBaiduPlayer.hideDamuViewSend();
                    mBaiduPlayer.setDamuEnable(false);

                    if (dcm.isCutoutScreen()) {//刘海屏处理
                       /* int size = getResources().getDimensionPixelSize(R.dimen.insert_video_height);
                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,size);
                        params.addRule(RelativeLayout.BELOW,R.id.mTitileBar);
                        ViewGroup parent = findViewById(R.id.containerRoot);
                        ViewGroup content = findViewById(android.R.id.content);
                        content.removeView(mBaiduPlayer);
                        parent.addView(mBaiduPlayer,params);*/
                        mBaiduPlayer.setSystemUiVisibility(0);
                    }
                    if (programsFragment != null) {
                        programsFragment.scrollToPosition();
                    }

                } else {
                    if (dcm.isCutoutScreen()) {//用于处理华为刘海屏不能全屏到问题
                        /*ViewGroup parent = findViewById(R.id.containerRoot);
                        parent.removeView(mBaiduPlayer);
                        ViewGroup content = findViewById(android.R.id.content);
                        content.addView(mBaiduPlayer);*/
//                        mHideHandler.postDelayed(mHidePart2Runnable, 300);
                        mBaiduPlayer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE |
                                View.SYSTEM_UI_FLAG_FULLSCREEN |
                                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY /*|
                                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION*/);
                    }

                    UserInfo userInfo = UserInfo.getUserInfo(VideoLiveDetailActivity.this);
                    //如果是已经登录了的 就直接链接服务器了
                    if (articleItem.getIsBarrage() == 1 && userInfo.isLogin() && !TextUtils.isEmpty(userInfo.getRongyunToken()) && !TextUtils.isEmpty(chatroomId)) {
                        mBaiduPlayer.setDamuEnable(true);
                    } else {
                        mBaiduPlayer.setDamuEnable(false);
                    }

                }
            }
        });
    }

    @Override
    public void success(ArticleItemReciver data) {
        if (data.state && data.articleItem != null) {

            if (articleItem != null && articleItem.getId() == data.articleItem.getId()) {
                mTyReportEndTime=mTyReportStartTime=System.currentTimeMillis();
            }
            articleItem = data.articleItem;
            ReportKit.INSTANCE.escalationArticle(articleItem.getId()+"", articleItem.getTitle(),articleItem.getPublishdate(),articleItem.getAddUser());
            UserRecommend.addItemKeyWord(articleItem, this);
            //    badgeView.setText(articleItem.getCommentCount() + "");
            refreshBottomStyle(articleItem, 1);
            linearShareLayout.setVisibility(View.GONE);
            liveChannelName.setText(articleItem.getTitle());
            UserInfo userInfo = UserInfo.getUserInfo(this);

            //如果是已经登录了的 就直接链接服务器了
            if (articleItem.getIsBarrage() == 1 && userInfo.isLogin() && !TextUtils.isEmpty(userInfo.getRongyunToken())) {
                //取聊天室id
                chatroomId = data.chatRoomId;
                String token = null;
                token = userInfo.getRongyunToken();
                /*if (!TextUtils.isEmpty(chatroomId)) {
                    danmu4RongYun = new DanMu4RongYun(token, chatroomId, this, mBaiduPlayer);
                    danmu4RongYun.id = articleItem.getVid();
                    danmu4RongYun.connectRongYun();
                }*/
            }
            if (TextUtils.isEmpty(articleItem.getGoodsID())) {
                videoPayUtil.showPaidView();
            } else {
                videoPayUtil.judgeShowPayView(articleItem);
            }
            setVideoPlayerData();
            CDPTrackReportManager.getInstance().LiveChannelStartPlay(articleItem);
            mBaiduPlayer.showVideoTitleInfo(articleItem.getTitle());
            setVideoContent(articleItem.getVideo());
        } else {
            mBaiduPlayer.setErrorViewVisible(View.VISIBLE);
        }
//        setComponent(data.components);
        Log.i(TAG, "addComponentList addComponentList");
        articleItem.mShowSwitch = mShowSwitch;
        NewsDetailComponentUtils.addComponentList(mRelateRootView, data.components, articleItem, this, getSupportFragmentManager(), 1, this);
        programsFragment = (ComponentLiveListFragment) getSupportFragmentManager().findFragmentByTag("ComponentLiveListFragment");
        AddMedalStatistics.addMedalStatistics(this); //勋章统计
        startAddIntegralCounter();
        broccoliLayout.setVisibility(View.GONE);
        mErrorView.setVisibility(View.GONE);
    }

    private void startAddIntegralCounter(){
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null) {
                    return;
                }
                Addintegral.addintegral(VideoLiveDetailActivity.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
            }
        });
    }

    private void setVideoContent(String videoStr) {
        try {

            mBaiduPlayer.isLive = true;
            JSONObject video = new JSONObject(videoStr);

            videoPlayObj.getMediaItem().clear();
            videoPlayObj.setTitle(articleItem.getTitle());
            videoPlayObj.setVID(articleItem.getVid());
            String poster = video.optString("poster", "");
            if (TextUtils.isEmpty(poster))
                mBaiduPlayer.setPoster(articleItem.getLogo(), AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.img_cut);
            else
                mBaiduPlayer.setPoster(poster, AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.img_cut);
            String appCustomParams = articleItem.getAppCustomParams();
            JSONObject jsonObject = new JSONObject(appCustomParams);
                JSONObject movie = jsonObject.optJSONObject("movie");
                String path = movie.optString("livePath");
                String liveDomain = movie.optString("liveDomain");
                String liveId = movie.optString("liveId");
                String txFlag = movie.optString("txFlag");
                if ("1".equals(txFlag)){
                    String encodeUrl = GetUrlToolKt.encodeUrl(liveDomain,liveId);
                    VideoLineItem lineItem = new VideoLineItem();
                    lineItem.setAddress(encodeUrl);
                    lineItem.setQuality("高清");
                    lineItem.setCdnEncypt(cdnEncypt);
                    if (!TextUtils.isEmpty(lineItem.getAddress()))
                        videoPlayObj.getMediaItem().add(lineItem);
                }else{
                    JSONArray tsAddress;
                    String currentTenantid = getResources().getString(R.string.tenantid);
                    if (currentTenantid.equals(getResources().getString(R.string.tenant_jiangxi))) {
                        tsAddress = video.optJSONArray("android");
                    } else {
                        tsAddress = video.optJSONArray("ANDROID");
                        if (tsAddress == null) {
                            tsAddress = video.optJSONArray("PC");
                        }
                    }
                    cdnEncypt = video.optString("cdnConfigEncrypt");
                    videoPlayObj.setCdn_iv(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
                    videoPlayObj.setCdn_key(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key);
                    if (tsAddress != null)
                        for (int i = 0; i < tsAddress.length(); i++) {
                            JSONObject line = tsAddress.optJSONObject(i);
                            String title = line.optString("title");
                            String url;
                            if (currentTenantid.equals(getResources().getString(R.string.tenant_jiangxi))) {
                                url = line.optString("liveStream");
                            } else {
                                url = line.optString("url");
                            }
                            lineMap.put(title, line.optString(LiveMediaPlayBackInvoker.ReviewUrl));
                            VideoLineItem lineItem = new VideoLineItem();
                            lineItem.setAddress(url);
                            lineItem.setQuality(title);
                            lineItem.setCdnEncypt(cdnEncypt);
                            if (!TextUtils.isEmpty(lineItem.getAddress()))
                                videoPlayObj.getMediaItem().add(lineItem);
                        }
                }
            mBaiduPlayer.getMediaObjs().clear();
            mBaiduPlayer.addMediaObjs(videoPlayObj);
            if (videoPlayObj.getMediaItem().size() > 0) {
                mBaiduPlayer.playVideobj(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "" + e.getMessage());
            mBaiduPlayer.setErrorViewVisible(View.VISIBLE);
        }
    }


    @Override
    protected void onDestroy() {
        CDPTrackReportManager.getInstance().LiveChannelStopPlay(articleItem,mBaiduPlayer.getcurrentPlayPosition()-startPosition);
        super.onDestroy();
        updateHandle.removeMessages(1);
        if (readStatusInvoker != null)
            readStatusInvoker.destory();
        readStatusInvoker = null;

        if (mBaiduPlayer != null) {
            mBaiduPlayer.stop();
            mBaiduPlayer.onUnregisterReceiver();
        }
        if (newsDetailInvoker != null)
            newsDetailInvoker.destory();
        newsDetailInvoker = null;
        if (liveReplayBroadcast != null) {
            liveReplayBroadcast.liveReplayHandle = null;
            LocalBroadcastManager.getInstance(this).unregisterReceiver(liveReplayBroadcast);
        }
        liveReplayBroadcast = null;
        liveMediaPlayBackInvoker.destory();


//        if (commentDialogFram != null) {
//            commentDialogFram.dismiss();
//            commentDialogFram.destory();
//        }

        try {
            unregisterReceiver(powerStateReciver);
        } catch (Exception ex) {
        }
    }


    @Override
    public void fault(Object data) {
        mBaiduPlayer.setErrorViewVisible(View.VISIBLE);
    }

    /**
     * 链接融云
     */
    protected void connectRongYun() {
        String token = null;
        UserInfo userInfo = UserInfo.getUserInfo(this);
        if (userInfo.isLogin()) {
            token = userInfo.getRongyunToken();
        }
        /*//如果是已经登录了的 就直接链接服务器了
        if (userInfo.isLogin() && danmu4RongYun != null && !danmu4RongYun.isHadDoConnectAction()) {
            danmu4RongYun.token = token;
            danmu4RongYun.connectRongYun();
        }*/
    }


    class LivePlayBackUrlReciver implements DataInvokeCallBack<BaseMessageReciver> {

        @Override
        public void success(BaseMessageReciver data) {
            Log.w(TAG, "LivePlayBackUrlReciver success");
            if (data.state) {
                JSONObject reciveData = data.orginData.optJSONObject("data");
                if (reciveData != null && !TextUtils.isEmpty(reciveData.optString(LiveMediaPlayBackInvoker.Url))) {
                    String url = reciveData.optString(LiveMediaPlayBackInvoker.Url);
                    mBaiduPlayer.setErrorViewVisible(View.GONE);
                    mBaiduPlayer.stop();
                    VideoPlayObj replayObj = new VideoPlayObj();
                    VideoLineItem lineItem = new VideoLineItem();
                    lineItem.setCdnEncypt(null);
                    replayObj.setCdn_iv(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
                    replayObj.setCdn_key(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key);
                    lineItem.setAddress(url);
                    lineItem.setQuality(getString(R.string.standard_quility));
                    replayObj.getMediaItem().add(lineItem);
                    mBaiduPlayer.getMediaObjs().clear();
                    mBaiduPlayer.addMediaObjs(replayObj);
                    mBaiduPlayer.setAutoPlay(true);
                    if (replayObj.getMediaItem().size() > 0) {
                        mBaiduPlayer.isLiveReplay = true;
                        mBaiduPlayer.setBegin(true);
                        mBaiduPlayer.setLoadingViewBgTransparent();
                        mBaiduPlayer.playVideobj(0);
                    }
                    mBaiduPlayer.onLookBackResult(true);
                } else {
                    mBaiduPlayer.onLookBackResult(false);
                    ToastUtil.show(VideoLiveDetailActivity.this, R.string.getplaybackurlerror);
                }
            } else {
                mBaiduPlayer.onLookBackResult(false);
            }

        }

        @Override
        public void fault(Object data) {
            Log.w(TAG, "LivePlayBackUrlReciver fault");
            ToastUtil.show(VideoLiveDetailActivity.this, R.string.getplaybackurlerror);
            mBaiduPlayer.onLookBackResult(false);
        }

    }

    protected void selectLiveTableChild(int tableIndex, int childIndex) {
        fragment.selectLiveTableChild(tableIndex, childIndex);
    }


    private Handler updateHandle = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (programList != null && programList.size() > 0) {
                    if (msg.arg1 < programList.size() - 1) {
                        ProgramListItem item2 = programList.get(msg.arg1 + 1);
                        handleItem(item2);
                        if (programsFragment != null)
                            programsFragment.freshAdapter(item2);
                    }else{
                        updateHandle.removeMessages(1);
                    }
                }
            }
        }
    };

    int index = 0;
    /**
     * 处理回看或者切换到直播
     */
    @Override
    public void handleItem(ProgramListItem item) {
        try {
            updateHandle.removeMessages(1);
            if (programList != null) {
                for (int i = 0; i < programList.size(); i++) {
                    if (programList.get(i).getId() == item.getId()) {
                        index = i;
                        break;
                    }
                }
            }
            updateHandle.postDelayed(() -> {
                long now = System.currentTimeMillis();
                if (item.getStarttime()!= null && item.getEndtime()!= null){
                Date startTime = DateParse.parseDate(item.getStarttime(), null);
                Date endDate = DateParse.parseDate(item.getEndtime(), null);
                long delay = 0L;
                if (now > endDate.getTime()){//回看
                    delay = endDate.getTime() - startTime.getTime();
                }else{
                    if (now > startTime.getTime()){
                        delay =  endDate.getTime() - now;
                    }else{
                        delay =  endDate.getTime() - startTime.getTime();
                    }
                }
                if (delay > 0L) {
                    Message msg = new Message();
                    msg.what = 1;
                    msg.arg1 = index;
                    updateHandle.sendMessageDelayed(msg, delay);
                }

                }
            }, 0);
            mBaiduPlayer.setErrorViewVisible(View.GONE);
            GuideItemState state;
            if (item.getPlayerStart() > 0L) { //startLong！=0 说明是来自进度条节目单
                if (System.currentTimeMillis() > item.getPlayerStart()) {
                    state = GuideItemState.REPLAY;
                } else {
                    state = GuideItemState.LIVE;
                }
            } else if (item.getPlayerStart() == -1) {
                state = GuideItemState.LIVE;
            } else {
                state = ProgramListItem.getItemState(item);
            }
            if (item.getIsPlaying() == 0) {
                mBaiduPlayer.stop();
                if (!TextUtils.isEmpty(item.placeholder))
                    mBaiduPlayer.setLiveIvPoser(item.placeholder, 0);
                else
                    mBaiduPlayer.setLiveIvPoser(articleItem.getLogo(), 0);
                if (GuideItemState.REPLAY == state) {
                    if (item.getPlayerStart() == 0L) {  //startLong==0 说明不是来自进度条节目单
                        mBaiduPlayer.setProgramComponentLookBack(item.getStarttime());
                    }
                }
            } else {
                mBaiduPlayer.setAutoPlay(true);
                mBaiduPlayer.setLiveIvPoser(item.placeholder, 8);
                Set<Entry<String, String>> keySet = lineMap.entrySet();
                Iterator<Entry<String, String>> iterator = keySet.iterator();

                if (GuideItemState.REPLAY == state) {

                    while (iterator.hasNext()) {
                        Entry<String, String> entry = iterator.next();
                        String url = entry.getValue();

                        Date startDate;
                        Date endDate = null;
                        if (item.getPlayerStart() != 0L) {
                            startDate = new Date(item.getPlayerStart());
                        } else {
                            startDate = DateParse.parseDate(item.getStarttime(), null);
                            endDate = DateParse.parseDate(item.getEndtime(), null);
                        }

                        long end;
                        if (endDate != null) {
                            end = endDate.getTime();
                        } else {
                            end = 0L;
                        }
                        AuthMode mode = URLAuth.EncrptMode(cdnEncypt, AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key, AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
                        liveMediaPlayBackInvoker.getLiveUrlPlayBackUrl(url, mode != null ? mode.getCode() : "", startDate.getTime(), end);

                        if (item.getPlayerStart() == 0L) {  //startLong==0 说明不是来自进度条节目单
                            mBaiduPlayer.setProgramComponentLookBack(item.getStarttime());
                        }
                        break;
                    }
                } else if (GuideItemState.LIVE == state) {
                    mBaiduPlayer.getMediaObjs().clear();
                    mBaiduPlayer.isLiveReplay = false;
                    mBaiduPlayer.addMediaObjs(videoPlayObj);
                    if (videoPlayObj.getMediaItem().size() > 0) {
                        mBaiduPlayer.setBegin(true);
                        mBaiduPlayer.playVideobj(0);
                    }
                    if (item.getPlayerStart() == 0L) {  //startLong==0 说明不是来自进度条节目单
                        mBaiduPlayer.setProgramComponentLookBack(null);
                    }
                    mBaiduPlayer.onLookBackResult(true);
                }
                setVideoPlayerData();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void getProgram(List<Map<String, List<ProgramListItem>>> data) {
        String videoUrl = null;
        if (videoPlayObj.getMediaItem().size() > 0)
            videoUrl = videoPlayObj.getMediaItem().get(0).getAddress();
        for (int index = 0; index < data.size(); index++) {
            String key = data.get(index).keySet().iterator().next();
            List<ProgramListItem> value = data.get(index).get(key);
            ArrayList<ProgramListItemX> programListItemXs = new ArrayList<ProgramListItemX>();
            for (int i = 0; value != null && i < value.size(); i++) {
                ProgramListItem item = value.get(i);
                //				item.setUrl(videoUrl);
                //				String starttime="&starttime=";
                //				String endtime="&endtime=";
                //				//			String shifttime="&shifttime=";
                //				Date startDate=DateParse.parseDate(item.getStarttime(),null);
                //				Date endDate=DateParse.parseDate(item.getEndtime(),null);
                //				//			shifttime+=""+startDate.getTime();
                //				starttime+=""+startDate.getTime();
                //				endtime+=""+endDate.getTime();
                //				String backUrl=videoUrl;
                //				if(backUrl.contains("?")==false)
                //					backUrl=backUrl.concat("?");
                //				backUrl=backUrl+starttime+endtime;//+shifttime;
                ProgramListItemX programListItemX = new ProgramListItemX();
                programListItemX.parse(item);
                //				programListItemX.setUrlBack(backUrl);
                programListItemXs.add(programListItemX);
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == MemberActivity.REQUEST_CODE && intent != null
                && intent.getBooleanExtra(MemberActivity.REQUEST_KEY, false)) {
            videoPayUtil.judgeShowPayView(articleItem);
        }
    }


    public void gotoCommentActivity() {
        Intent intent = new Intent();
        intent.putExtra("data", articleItem);
        intent.setClass(this, XCommentActivity.class);
        startActivity(intent);
    }


    ReadStatusInvoker readStatusInvoker;

    public void readStatus() {
        readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<ReadDataReciver>() {
            @Override
            public void success(ReadDataReciver data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, data.virtualIncrement);
            }

            @Override
            public void fault(Object data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, AnalysisUtils.DefaultVirtualIncrement);
            }
        });
        readStatusInvoker.readStatistics(articleItem.getId() + "", 1);
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readEnter(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readExit(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }


    @Override
    public void noNetwork() {
        //  mErrorView.setVisibility(View.VISIBLE);
        //emptyTipsText.setText("网络请求失败，请点击重试");
        mErrorView.setOnClickListener(v -> {
            if (hasNetWork)
                getVideoDetail();
            else showNetWorDialog();
        });
    }

    @Override
    public void onLookBackTimeStampChanged(long time) {
        mBaiduPlayer.getLoadingViewControl().hidePoster();
        ProgramListItem item;
        if (programsFragment != null) {
            item = programsFragment.setPlayingStartTime(time);
        } else item = new ProgramListItem();
        if (item != null) {
            item.setPlayerStart(time);
            handleItem(item);
            if (time == -1){
                if (programsFragment != null)
                    programsFragment.freshAdapter(item);
            }
        }
    }

    private List<ProgramListItem> programList;

    public void setPrograms(List<ProgramListItem> programList) {
        this.programList = programList;
        List<IProgram> programs = new ArrayList();
        for (ProgramListItem program : programList) {
            programs.add(new ProgramMod(program.getName(), program.getStarttime()));
        }
        mBaiduPlayer.setProgramList(programs);
    }

    public void freshShiled(ProgramListItem item) {
        handleItem(item);
    }

    @Override
    public void finish() {
        super.finish();
        ReportKit.INSTANCE.escalationArticleTime();
        if (articleItem!=null&&mTyReportStartTime>0) {
            mTyReportEndTime=System.currentTimeMillis();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void restorePause(NotifyMicroEvent event){
        //防止点击home键，评论框pause了，视频也应该pause
        if (mBaiduPlayer != null){
            if (event.getPlay())
                mBaiduPlayer.resume();
            else
                mBaiduPlayer.pause();
        }
    }
}